package com.wish.group05.finance.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.group05.base.dto.CheckBatchConfirmRequestDto;
import com.wish.group05.base.dto.CwCheckBatchDetailForm;
import com.wish.group05.base.dto.CwCheckBatchDetailRequestDto;
import com.wish.group05.base.dto.CwCheckBatchDetailResponseDto;
import com.wish.group05.base.entity.CwCheckBatch;
import com.wish.group05.base.entity.CwCheckBatchDetail;
import com.wish.group05.base.service.ICwCheckBatchDetailService;
import com.wish.group05.base.service.ICwCheckBatchService;
import com.wish.group05.finance.dto.CwCheckBatchDetailDto;
import com.wish.group05.finance.dto.CwCheckBatchDto;
import com.wish.group05.system.api.RemoteDictDataService;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.wish.group05.common.log.annotation.Log;
import com.wish.group05.common.log.enums.BusinessType;
import com.wish.group05.common.security.annotation.PreAuthorize;
import com.wish.group05.common.core.web.controller.BaseController;
import com.wish.group05.common.core.web.domain.AjaxResult;
import com.wish.group05.common.core.utils.poi.ExcelUtil;
import com.wish.group05.common.core.web.page.TableDataInfo;

/**
 * 对账批次Controller
 * 
 * @author wish
 * @date 2022-05-29
 */
@RestController
@RequestMapping("/batch")
public class TCwCheckBatchController extends BaseController
{
    @Autowired
    ICwCheckBatchService cwCheckBatchService;
    @Resource
    RemoteDictDataService remoteDictDataService;
    @Autowired
    ICwCheckBatchDetailService cwCheckBatchDetailService;

    /**
     * 重新对账
     * @param checkBatchConfirmRequestDto
     * @return
     */
    @PostMapping("forSure")
    public AjaxResult checkBillBatch(@RequestBody CheckBatchConfirmRequestDto checkBatchConfirmRequestDto) {

        try {
            cwCheckBatchService.checkBillBatch(checkBatchConfirmRequestDto);
            return AjaxResult.success("重新对账成功");
        } catch (NullPointerException n) {
            n.printStackTrace();
            return AjaxResult.error(n.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("重新对账失败");
        }

    }


    /**
     * 对账确认
     * @param checkBatchConfirmRequestDto
     * @return
     */
    @PostMapping("moneyForSure")
    public AjaxResult moneyForSure(@RequestBody CheckBatchConfirmRequestDto checkBatchConfirmRequestDto) {
        try {
            cwCheckBatchService.checkBatchConfirm(checkBatchConfirmRequestDto);
            return AjaxResult.success("对账确认成功");
        } catch (RuntimeException runtimeException) {
            runtimeException.printStackTrace();
            return AjaxResult.error(runtimeException.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("对账确认失败");
        }
    }


    @GetMapping("getDict")
    public AjaxResult getDict() {
        HashMap<String, Object> map = new HashMap<>();
        AjaxResult tradeResult = remoteDictDataService.getDictDataList("sys_trade_result");
        map.put("tradeResultList",tradeResult);
        AjaxResult hasDiff = remoteDictDataService.getDictDataList("sys_has_diff");
        map.put("hasDiffList",hasDiff);
        AjaxResult processState = remoteDictDataService.getDictDataList("sys_process_state");
        map.put("processStateList",processState);
        AjaxResult payWay = remoteDictDataService.getDictDataList("sys_pay_way");
        map.put("payWayList",payWay);
        return AjaxResult.success(map);
    }

    @GetMapping("showBatch")
    public TableDataInfo showBatch(CwCheckBatchDetailForm cwCheckBatchDetailForm) {
        QueryWrapper<CwCheckBatchDetail> wrapper = new QueryWrapper<>();
        /**
         * 批次号（yyyymmdd001）
         */
        if (StringUtils.isNoneBlank(cwCheckBatchDetailForm.getBatchNo())) {
            wrapper.eq("batch_no",cwCheckBatchDetailForm.getBatchNo());
        }
        //渠道名称：拉卡拉 交易渠道：暂时固定拉卡拉。
        if (StringUtils.isNoneBlank(cwCheckBatchDetailForm.getTradeQudao())) {
            wrapper.like("trade_qudao",cwCheckBatchDetailForm.getTradeQudao());
        }
        //交易结果：接口回调或者返回的结果 1:处理中，2:成功，3:失败。
        if (cwCheckBatchDetailForm.getTradeResult()!=null) {
            wrapper.eq("trade_result",cwCheckBatchDetailForm.getTradeResult());
        }
        //交易金额：支付订单金额
        if (StringUtils.isNoneBlank(cwCheckBatchDetailForm.getAmount())) {
            wrapper.like("amount",cwCheckBatchDetailForm.getAmount());
        }
        //交易日期（开始）：渠道支付时间
        if (StringUtils.isNoneBlank(cwCheckBatchDetailForm.getStartDate())) {
            wrapper.ge("trade_date_zf",cwCheckBatchDetailForm.getStartDate());
        }
        //交易日期（结束）：渠道支付时间
        if (StringUtils.isNoneBlank(cwCheckBatchDetailForm.getEndDate())) {
            wrapper.le("trade_date_zf",cwCheckBatchDetailForm.getEndDate());
        }
        //支付方式,同流水里面一样
        if (cwCheckBatchDetailForm.getPayWay() != null) {
            wrapper.eq("pay_way",cwCheckBatchDetailForm.getPayWay());
        }
        //交易账户
        if (StringUtils.isNoneBlank(cwCheckBatchDetailForm.getTradeAccount())) {
            wrapper.like("trade_account",cwCheckBatchDetailForm.getTradeAccount());
        }
        //是否差错
        if (cwCheckBatchDetailForm.getHasDiff() != null) {
            wrapper.eq("has_diff",cwCheckBatchDetailForm.getHasDiff());
        }
        //差错处理结果
        if (cwCheckBatchDetailForm.getProcessState() != null) {
            wrapper.eq("process_state",cwCheckBatchDetailForm.getProcessState());
        }
        wrapper.eq("del_flg",0);

        startPage();
        List<CwCheckBatchDetail> list = cwCheckBatchDetailService.list(wrapper);
        if (list == null) {
            logger.info("----查询对账明细数据无.");
            logger.info("selectCheckBatchDetail查询对账明细 End.");
            return getDataTable(new ArrayList<CwCheckBatchDetail>());
        }
        logger.info("selectCheckBatchDetail查询对账明细 End.");
        return getDataTable(list);
    }

    /**
     * 获取是否完成对账集合
     * @return
     */
    @GetMapping("getCompleteStateList")
    public AjaxResult getCompleteStateList() {
        //获取是否完成对账集合
        AjaxResult completeState = remoteDictDataService.getDictDataList("sys_complete_state");
        return completeState;
    }

    /**
     * 获取账单类型集合
     * @return
     */
    @GetMapping("getBillTypeList")
    public AjaxResult getBillTypeList() {
        AjaxResult completeState = remoteDictDataService.getDictDataList("sys_bill_type");
        return completeState;
    }
    /**
     * 获取生成方式集合
     * @return
     */
    @GetMapping("getCreateTypeList")
    public AjaxResult getCreateTypeList() {
        AjaxResult completeState = remoteDictDataService.getDictDataList("sys_create_type");
        return completeState;
    }

    /**
     * 查询对账批次列表
     */
    @PreAuthorize(hasPermi = "finance:batch:list")
    @GetMapping("/list")
    public TableDataInfo list(CwCheckBatchDto cwCheckBatchDto)
    {
        QueryWrapper<CwCheckBatch> wrapper = new QueryWrapper<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        if (cwCheckBatchDto.getBillDay()!=null) {
            String billDay = sdf.format(cwCheckBatchDto.getBillDay());
            wrapper.ge("bill_day",billDay);
        }
        if (cwCheckBatchDto.getBillDay1() != null) {
            String billDay1 = sdf.format(cwCheckBatchDto.getBillDay1());
            wrapper.le("bill_day",billDay1);
        }
        wrapper.eq("del_flg",0);
        wrapper.orderByDesc("bill_day");
        startPage();
        List<CwCheckBatch> list = cwCheckBatchService.list(wrapper);
        return getDataTable(list);
    }


}
